<template>
   <Modal
        v-model="show"
        :title="type==1?'创建技能树':'修改技能树'"
        @on-ok="ok"
        :mask-closable="false"
        :loading="load"
        @on-cancel="cancel">
        <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="80">
        <FormItem label="名称" prop="name">
            <Input v-model="formValidate.name" placeholder="输入技能树名称"></Input>
        </FormItem>
        <FormItem label="描述" prop="description">
            <Input v-model="formValidate.description" type="textarea" :autosize="{minRows: 2,maxRows: 5}" placeholder="输入技能树描述"></Input>
        </FormItem>
        </Form>
    </Modal>     
</template>
<script>
import { addSkill, modifySkill } from '@/api/selfStudy/skill.js'
import { validateName,validateName128 } from '@/libs/reg';
export default{
  data(){
    return {
      load:true,
      show:false,
      type:1,//1 创建2 修改
      formValidate:{
        name:'',
        description:'',
      },
      ruleValidate:{
        name:[
          { required: true, message: '名称不能为空', trigger: 'change' },
          { validator: validateName128, trigger: 'change' }
        ],
        description:[
         {  max: 200, message: '描述信息不能超过200个字符', trigger: 'change' }
        ]
      }
    }
  },
  methods:{
    open(obj){
      this.initForm();
      if(obj){
        this.type = 2//修改
        this.formValidate = {...obj}//表单赋值
      }else{
        this.type = 1
      }
      this.show = true;
    },
    setLoad(){
        this.load = false;
        this.$nextTick(()=>{
        this.load = true;
      })
    },
    ok(){
      this.$refs.formValidate.validate((valid) => {
          if (valid) {
            let apiRequest,txt;
            let obj = {
                "description": "",
                "id": "",
                "name": "",
            }
            const {name,description,id} = this.formValidate;
            if(this.type==1){
              apiRequest = addSkill;
              txt='创建';
              obj = {...obj,name,description};
              delete obj.id;
            }else{
              apiRequest = modifySkill;
              txt='修改'
              obj = {...obj,name,description,id}
            }
            apiRequest(obj).then(res=>{
              if(res.code==1){
                this.$Message.info(txt+'成功');
                 this.show = false;
                this.$emit('refreshList')
              }else{
                this.$Message.error(res.message)
              }
            }).finally(()=>{
              this.setLoad()
            })
          } else {
              this.$Message.error('表单输入有误，请按提示输入!');   
              this.setLoad()  
            }
          })
    },
    cancel(){
      this.show = false;
      this.initForm();
    },
    initForm(){
      this.formValidate={
        name:'',
        description:'',
      };
      this.$refs.formValidate.resetFields();
    }
  }
}
</script>
